/*
 * @Author: yjp
 * @Date: 2022-03-25 09:54:30
 */
import { GroupOutlined, KeyOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin, Dropdown, message } from 'antd';
import styles from './index.less';
import type { MenuInfo } from 'rc-menu/lib/interface';
import { useKeycloak } from '@react-keycloak/web';
import { useEffect, useMemo, useState } from 'react';
import avatarUrl from './avatar.png';
import MegaUpdateForm from '../MegaUpdateForm';
import { getUser, updatePassword, updateUser } from '@/pages/System/User/api';
import { InfoForm } from '../UserForm/InfoForm';
import { ModalForm } from '@ant-design/pro-form';
import { PasswordForm } from '../UserForm/PasswordForm';
import { UserEntity } from '@/pages/System/User/entities';

interface IKCUserInfo {
    email: string;
    family_name: string;
    given_name: string;
    name: string;
    preferred_username: string;
    sub: string;
}

export default () => {

    const { keycloak } = useKeycloak();

    const [kcUser, setKCUser] = useState<IKCUserInfo>();
    const [currentUser, setCurrentUser] = useState<UserEntity>();
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [passwordModalVisible, handlePasswordModalVisible] = useState<boolean>(false);
    const [kcLoading, setKCLoading] = useState<boolean>(false);
    const [currentUserLoading, setCurrentUserLoading] = useState<boolean>(false);

    const onMenuClick = (event: MenuInfo) => {
        const { key } = event;
        if (key === 'settings') {
            handleUpdateModalVisible(true)
            return;
        }
        if (key === 'password') {
            handlePasswordModalVisible(true);
            return;
        }
        if (key === 'logout') {
            keycloak.logout();
            return;
        }
    }

    const initKCUser = async () => {
        setKCLoading(true);
        let info
        try {
            info = await keycloak.loadUserInfo();
        } catch (error) {

        } finally {
            setKCLoading(false)
        }
        if (!info) {
            setTimeout(() => {
                initKCUser()
            }, 2000)
        } else {
            setKCUser(info as IKCUserInfo)
        }
    }

    const initCurrentUser = async (id: string) => {
        setCurrentUserLoading(true);
        try {
            const info = await getUser(id);
            setCurrentUser(info)
        } catch (error) {

        } finally {
            setCurrentUserLoading(false)
        }
    }

    useEffect(() => {
        initKCUser()
    }, [])

    useEffect(() => {
        if (kcUser?.sub) {
            initCurrentUser(kcUser.sub)
        }
    }, [kcUser?.sub])

    const groups = useMemo(() => {
        const newGroups: { id: string; name: string; }[] = []
        if (!currentUser) {
            return newGroups
        }
        currentUser.groups.forEach((role) => {
            const { tenant_id, tenant_name } = role
            if (!~newGroups.findIndex((item) => tenant_id === item.id)) {
                newGroups.push({
                    id: tenant_id,
                    name: tenant_name
                })
            }

        })
        return newGroups
    }, [currentUser])

    if (kcLoading || currentUserLoading || !kcUser || !currentUser) {
        return (
            <span className={`${styles.action} ${styles.account}`}>
                <Spin
                    size="small"
                    style={{
                        marginLeft: 8,
                        marginRight: 8,
                    }}
                />
            </span>
        );
    }

    const menuHeaderDropdown = (
        <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
            <Menu.Item key="settings">
                <SettingOutlined />
                个人设置
            </Menu.Item>
            <Menu.Item key="password">
                <KeyOutlined />
                修改密码
            </Menu.Item>
            <Menu.SubMenu key="groups" icon={<GroupOutlined />} title="切换租户" >
                {groups.map((group) => (<Menu.Item key={group.id}>{group.name}</Menu.Item>))}
            </Menu.SubMenu>
            <Menu.Divider />
            <Menu.Item key="logout">
                <LogoutOutlined />
                退出登录
            </Menu.Item>
        </Menu>
    );
    return (
        <>
            <Dropdown overlay={menuHeaderDropdown}>
                <span className={`${styles.action} ${styles.account}`}>
                    <Avatar size="small" className={styles.avatar} src={avatarUrl} alt="avatar" />
                    <span className={`${styles.name} anticon`}>{kcUser.name}</span>
                </span>
            </Dropdown>
            <MegaUpdateForm
                handleModalVisible={handleUpdateModalVisible}
                modalVisible={updateModalVisible}
                title={'编辑用户'}
                currentEntity={{ id: kcUser.sub }}
                getEntityAction={getUser}
                updateEntityAction={updateUser}
                onSuccess={initKCUser}
            >
                <InfoForm isCreate={false} />
            </MegaUpdateForm>
            <ModalForm
                title={'修改密码'}
                visible={passwordModalVisible}
                onVisibleChange={handlePasswordModalVisible}
                modalProps={{
                    destroyOnClose: true,
                }}
                onFinish={async (value) => {
                    const { old_password, new_password, need_renew = false } = value;
                    const newValue = { id: kcUser.sub, old_password, new_password, need_renew }
                    const hide = message.loading('正在更新');
                    try {
                        await updatePassword(newValue);
                        hide();
                        message.success('更新成功, 请重新登录');
                        handlePasswordModalVisible(false);
                        keycloak.logout();
                    } catch (error) {
                        hide();
                        message.error('更新失败');
                    }
                }}
            >
                <PasswordForm isPersonal={true} />
            </ModalForm>
        </>
    );
};
